

package cn.shengchao.dubbo.api.distribute;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.base.utils.SecureUtils;
import cn.shengchao.dubbo.bi.InviteUnifiedCreateProcessor;
import cn.shengchao.examstar.distribute.infrastrure.po.*;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.base.TransResult;
import cn.shengchao.examstar.rpc.distribute.cs.UserCs;
import cn.shengchao.examstar.distribute.acl.ports.repositories.IDistributeRepository;
import cn.shengchao.examstar.distribute.infrastrure.query.SaleAmountQuery;
import cn.shengchao.examstar.distribute.infrastrure.service.*;
import cn.shengchao.examstar.distribute.infrastrure.vo.DistributeContentUserGroup;
import cn.shengchao.examstar.distribute.infrastrure.vo.DistributeSale;
import cn.shengchao.examstar.distribute.infrastrure.vo.DistributeSaleUserGroup;
import cn.shengchao.examstar.distribute.model.DistributeNodeRoleChainExistModel;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeNodeRoleChainDomainService;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeNodeRoleChainExistLoader;
import cn.shengchao.examstar.rpc.distribute.bi.DistributeNodeBI;
import cn.shengchao.examstar.rpc.distribute.dto.DistributeNodeInfoChangeNodeDto;
import cn.shengchao.examstar.rpc.distribute.dto.UserInviteDto;
import cn.shengchao.examstar.rpc.distribute.enums.*;
import cn.shengchao.examstar.rpc.distribute.req.DistributeNodeInfoQueryPage;
import cn.shengchao.examstar.rpc.distribute.req.DistributeNodePhoneCheckReq;
import cn.shengchao.examstar.rpc.distribute.req.DistributorQueryPage;
import cn.shengchao.examstar.rpc.distribute.req.DistributorStudentQueryPage;
import cn.shengchao.examstar.rpc.distribute.resp.*;
import cn.shengchao.examstart.user.acl.adapters.repositories.DeptRepository;
import cn.shengchao.examstart.user.acl.adapters.repositories.UserRepository;
import cn.shengchao.examstart.user.domain.entity.Dept;
import cn.shengchao.examstart.user.domain.entity.User;
import cn.shengchao.examstart.user.infrastructure.dao.UserDao;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;
import top.continew.starter.core.exception.BaseException;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;


/**
 * @program: examstarapi
 * @description: 分销节点商业整合服务
 * @author: Xiong weiqiang
 * @create: 2025-03-26 18:04
 */
@DubboService
@RequiredArgsConstructor
public class DistributeNodeBIService implements DistributeNodeBI {
    private final UserRepository userRepository;
    private final UserDao userDao;
    private final DistributeNodeRoleChainExistLoader distributeNodeRoleChainExistLoader;
    private final DistributeNodeRoleChainDomainService distributeNodeRoleChainDomainService;
    private final DistributeNodeInfoService distributeNodeInfoService;
    private final DistributeDeptInfoService distributeDeptInfoService;
    private final IDistributeRepository iDistributeRepository;
    private final DeptRepository deptRepository;
    private final DistributeUserInviteService distributeUserInviteService;
    private final DistributeOrderTaskSaleService distributeOrderTaskSaleService;
    private final DistributeOrderTaskContentService distributeOrderTaskContentService;
    private final DistributeDeptUserRoleBindService distributeDeptUserRoleBindService;
    private final InviteUnifiedCreateProcessor inviteUnifiedCreateProcessor;
    private final DistributeContentInfoService distributeContentInfoService;
    private final DistributeContentProductThirdService distributeContentProductThirdService;
    @Override
    public DistributeNodeInfoWithUpLevelRespEntity queryDistributeNodeInfoWithUpLevel(Long userId, Integer distributeType) {
        DistributeTypeEnum distributeTypeEnum=DistributeTypeEnum.getByType(distributeType);
        if (distributeTypeEnum!=null){
            DistributeNodeRoleChainExistModel existModel=distributeNodeRoleChainExistLoader.loadModelByUserIdByDeptChain(userId,distributeTypeEnum);
            if (existModel!=null&&existModel.getDistributeNodeInfo()!=null){
                DistributeNodeInfoWithUpLevelRespEntity distributeNodeInfoWithUpLevelRespEntity=new DistributeNodeInfoWithUpLevelRespEntity();
                DistributeNodeInfo distributeNodeInfo=distributeNodeInfoService.getById(existModel.getDistributeNodeInfo().getId());
                BeanUtil.copyProperties(distributeNodeInfo,distributeNodeInfoWithUpLevelRespEntity);
                DistributeNodeInfoWithUpLevelRespEntity upLevelRespEntity=BeanUtil.copyProperties(existModel.getUpLevelNodeInfo(),DistributeNodeInfoWithUpLevelRespEntity.class);
                distributeNodeInfoWithUpLevelRespEntity.setUpLevelNode(upLevelRespEntity);
                if (existModel.getDistributeNodeRole()!=null){
                    distributeNodeInfoWithUpLevelRespEntity.setPercentStable(existModel.getDistributeNodeRole().getPercentStable());
                }
                return distributeNodeInfoWithUpLevelRespEntity;
            }
        }
        return null;
    }
    @Transactional
    @Override
    public TransResult<String> changeContentDistributeUserUpLevel(Long userId, String distributeRoleCode, Long upperUserId) {

        DistributeContentRoleEnum localRole=DistributeContentRoleEnum.getByCode(distributeRoleCode);
        DistributeNodeRoleChainExistModel userExistModel =distributeNodeRoleChainExistLoader.loadModelByUserIdByDeptChain(userId,DistributeTypeEnum.TYPE_CTPD);
        if (StrUtil.isNotBlank(distributeRoleCode)&& DistributeContentRoleEnum.ROLE_CTPD_EMP.getCode().equals(distributeRoleCode)){
            //只有员工可以换上级
            if (userExistModel!=null&&userExistModel.getDistributeNodeRole()!=null&&DistributeContentRoleEnum.ROLE_CTPD_EMP.getCode().equals(userExistModel.getDistributeNodeRole().getRoleCode())){
                List<DistributeContentInfo> contentInfoList=distributeContentInfoService.list(Wrappers.lambdaQuery(DistributeContentInfo.class).eq(DistributeContentInfo::getAuthorUserId,userId).eq(DistributeContentInfo::getDataStatus,1));
                List<DistributeContentProductThird> thirdList=distributeContentProductThirdService.list(Wrappers.lambdaQuery(DistributeContentProductThird.class).eq(DistributeContentProductThird::getUserId,userId).eq(DistributeContentProductThird::getDataStatus,1));
                if (CollUtil.isNotEmpty(contentInfoList)||CollUtil.isNotEmpty(thirdList)){
                    return TransResult.fail("内容用户换绑错误：用户有内容代理，不能切换，需要先清除内容记录");
                }
                if (userExistModel.getUpLevelNodeInfo().getUserId().equals(upperUserId)){
                    return TransResult.fail("内容用户换绑错误：用户切换到内容机构是原部门，不需要切换");
                }
                Long deptId=distributeDeptUserRoleBindService.getDeptBindIdForUser(upperUserId,DistributeTypeEnum.TYPE_CTPD);
                if (deptId==null){
                    return TransResult.fail("内容用户换绑错误：用户切换到内容机构部门为空");
                }
                //内容员工换个部门
                distributeDeptUserRoleBindService.processUserDeptRole(DistributeTypeEnum.TYPE_CTPD, userId, deptId, SysRoleDistributeBindEnum.RB_CONTENT_EMPLOYEE.getSysRoleCode(), distributeRoleCode);
                userRepository.updateUserDept(userId,deptId);
                DistributeNodeInfoChangeNodeDto changeDistributeUserUpLevelNode=new DistributeNodeInfoChangeNodeDto();
                changeDistributeUserUpLevelNode.setDistributeType(DistributeTypeEnum.TYPE_CTPD);
                changeDistributeUserUpLevelNode.setUserId(userId);
                changeDistributeUserUpLevelNode.setUpLevelUserId(upperUserId);
                changeDistributeUserUpLevelNode.setUpLevelRoleCode(userExistModel.getUpLevelNodeInfo().getDistributeRoleCode());
                changeDistributeUserUpLevelNode.setPercentStable(userExistModel.getDistributeNodeRole().getPercentStable());
                distributeNodeRoleChainDomainService.changeDistributeUserUpLevelNode(changeDistributeUserUpLevelNode);
                return TransResult.success();
            }else {
                return TransResult.fail("内容用户换绑错误：原用户加载角色检查错误"+(localRole==null?"无":localRole.getDescription()));
            }
        }else{
            return TransResult.fail("内容用户换绑错误：原用户加载角色不支持"+(localRole==null?"无":localRole.getDescription()));
        }
    }

    @Transactional
    @Override
    public TransResult<String> changeSaleDistributeUserUpLevel(Long userId,  String distributeRoleCode, Long upperUserId) {
        DistributeNodeRoleChainExistModel userExistModel =distributeNodeRoleChainExistLoader.loadModelByUserIdByDeptChain(userId,DistributeTypeEnum.TYPE_SALE);
        DistributeSaleRoleEnum localRole=DistributeSaleRoleEnum.getByCode(distributeRoleCode);
        Long originNodeId=userExistModel.getDistributeNodeInfo().getId();

        if (userExistModel==null||userExistModel.getDistributeNodeRole()==null||!distributeRoleCode.equals(userExistModel.getDistributeNodeRole().getRoleCode())){
            String loadRoleDescription="无";
            if (userExistModel!=null&&userExistModel.getDistributeNodeRole()!=null){
                DistributeSaleRoleEnum loadRole=DistributeSaleRoleEnum.getByCode(userExistModel.getDistributeNodeRole().getRoleCode());
                loadRoleDescription= (loadRole==null?"无":loadRole.getDescription());
            }
            return TransResult.fail("用户换绑错误：原用户加载角色不匹配"+(localRole==null?"无":localRole.getDescription())+",加载角色为"+ loadRoleDescription);
        }
        if (userExistModel.getUpLevelNodeInfo()!=null&&userExistModel.getUpLevelNodeInfo().getUserId().equals(upperUserId)){
            return TransResult.fail("用户换绑错误：用户上级相同，不需要切换");
        }
        //修改邀请关系，贡献给加盟商
        UserInviteDto userInviteDto=new UserInviteDto();
        userInviteDto.setUserId(userId);
        userInviteDto.setInviteUserId(upperUserId);
        userInviteDto.setDistributeUserId(upperUserId);
        if (DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeRoleCode)||DistributeSaleRoleEnum.ROLE_SLMB.getCode().equals(distributeRoleCode)) {
            inviteUnifiedCreateProcessor.savePlatformUserInviteRecord(userInviteDto);
            Long originDpsdUserId=userExistModel.getUpLevelNodeInfo().getUserId();
            //批量更新用户分销关系到加盟商下
            distributeUserInviteService.batchUpdateUserInviteRecordForJms(userId,originDpsdUserId);
        }
        if (DistributeSaleRoleEnum.ROLE_SLMB.getCode().equals(distributeRoleCode)) {
            inviteUnifiedCreateProcessor.savePlatformUserInviteRecord(userInviteDto);
            //会员分销关系不动
        }
        if (upperUserId==0L){
            //用户改挂平台
            if (DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeRoleCode)) {
                return TransResult.fail("用户换绑错误：原用户员工是不能挂平台");
            }else {
                DistributeNodeInfo originUpperNodeInfo = userExistModel.getUpLevelNodeInfo();
                if (originUpperNodeInfo==null){
                    return TransResult.fail("用户换绑错误：原用户上级为空");
                }else {
                    changeSaleDistributeUserDeptRoleBindToPlatform(userId,distributeRoleCode);
                    //原来的上级不是平台，也不用动它。主要可能要切换用户的绑定部门。
                    DistributeNodeInfoChangeNodeDto changeDistributeUserUpLevelNode=new DistributeNodeInfoChangeNodeDto();
                    changeDistributeUserUpLevelNode.setUserId(userId);
                    changeDistributeUserUpLevelNode.setDistributeType(DistributeTypeEnum.TYPE_SALE);
                    changeDistributeUserUpLevelNode.setUpLevelUserId(upperUserId);
                    changeDistributeUserUpLevelNode.setUpLevelRoleCode(distributeRoleCode);

                    changeDistributeUserUpLevelNode.setPercentStable(userExistModel.getDistributeNodeRole().getPercentStable());
                    distributeNodeRoleChainDomainService.changeDistributeUserUpLevelNode(changeDistributeUserUpLevelNode);
                    return TransResult.success();
                }
            }
        }else{
            DistributeNodeRoleChainExistModel upperUserExistModel =distributeNodeRoleChainExistLoader.loadModelByUserIdByDeptChain(upperUserId,DistributeTypeEnum.TYPE_SALE);
            if (upperUserExistModel==null||upperUserExistModel.getDistributeNodeRole()==null){
                return TransResult.fail("用户换绑错误：上级用户加载角色检查错误"+upperUserId);
            }else {
                TransResult<String> result=checkSaleUpperRoleChange(distributeRoleCode,upperUserExistModel.getDistributeNodeRole().getRoleCode());
                if (!result.getSuccess()){
                    return result;
                }else {
                    changeSaleDistributeUserDeptRoleBindToUpUser(userId, distributeRoleCode, upperUserId, upperUserExistModel.getDistributeNodeInfo().getDistributeRoleCode());
                    DistributeNodeInfoChangeNodeDto changeDistributeUserUpLevelNode = new DistributeNodeInfoChangeNodeDto();
                    changeDistributeUserUpLevelNode.setUserId(userId);
                    changeDistributeUserUpLevelNode.setDistributeType(DistributeTypeEnum.TYPE_SALE);
                    changeDistributeUserUpLevelNode.setUpLevelUserId(upperUserId);
                    changeDistributeUserUpLevelNode.setUpLevelRoleCode(distributeRoleCode);
                    changeDistributeUserUpLevelNode.setPercentStable(userExistModel.getDistributeNodeRole().getPercentStable());
                    distributeNodeRoleChainDomainService.changeDistributeUserUpLevelNode(changeDistributeUserUpLevelNode);
                    return TransResult.success();
                }
            }
        }
    }
    private TransResult<String> checkSaleUpperRoleChange(String roleCode,String upperRoleCode){
        DistributeSaleRoleEnum localRole=DistributeSaleRoleEnum.getByCode(roleCode);
        DistributeSaleRoleEnum upperRole=DistributeSaleRoleEnum.getByCode(upperRoleCode);
        if (StrUtil.isBlank(roleCode)||StrUtil.isBlank(upperRoleCode)){
            return TransResult.fail("用户换绑错误：角色检查有空值，原用户："+(localRole==null?"无":localRole.getDescription())+"，上级用户："+(upperRole==null?"无":upperRole.getDescription()));
        }else {
            if (roleCode.equals(DistributeSaleRoleEnum.ROLE_DSPD.getCode())&&DistributeSaleRoleEnum.ROLE_MKMG.getCode().equals(upperRoleCode)){
                return TransResult.success();
            }
            if (roleCode.equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode())&&DistributeSaleRoleEnum.ROLE_DSPD.getCode().equals(upperRoleCode)){
                return TransResult.success();
            }
            if (roleCode.equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())&&DistributeSaleRoleEnum.ROLE_DSPD.getCode().equals(upperRoleCode)){
                return TransResult.success();
            }
            return TransResult.fail("用户换绑错误：角色检查错误，原用户："+(localRole==null?"无":localRole.getDescription())+"，不能换到上级用户："+(upperRole==null?"无":upperRole.getDescription()));
        }
    }
    @Override
    public DistributeNodePhoneCheckResult checkPhoneForDistributeCreate(DistributeNodePhoneCheckReq phoneCheckReq) {
        //手机号校验
        if (StrUtil.isBlank(phoneCheckReq.getPhone())) {
            return DistributeNodePhoneCheckResult.builder()
                    .checkResult(Boolean.FALSE)
                    .phone(phoneCheckReq.getPhone())
                    .message("手机号为空")
                    .build();
        }
        List<User> userList = userRepository.selectByPhone(phoneCheckReq.getPhone());
        if (CollUtil.isNotEmpty(userList)) {
            if (userList.size() > 1) {
                return DistributeNodePhoneCheckResult.builder()
                        .checkResult(Boolean.FALSE)
                        .phone(phoneCheckReq.getPhone())
                        .message("手机号用户账号异常")
                        .build();
            }
            Long userId = userList.getFirst().getId();
            DistributeNodeRoleChainExistModel existModel = distributeNodeRoleChainExistLoader
                    .loadModelByUserId(userId, DistributeTypeEnum.TYPE_SALE.getType());
            if (existModel != null) {
                return DistributeNodePhoneCheckResult.builder()
                        .checkResult(Boolean.FALSE)
                        .phone(phoneCheckReq.getPhone())
                        .message("手机号用户账号分销户已存在")
                        .build();
            }
        }
        return DistributeNodePhoneCheckResult.builder()
                .checkResult(Boolean.TRUE)
                .phone(phoneCheckReq.getPhone())
                .message("验证成功")
                .build();
    }



    @Override
    public PageResult<DistributeNodeInfoRespEntity> queryDistributeNodeInfoPageResult(DistributeNodeInfoQueryPage pageQuery) {
        PageResult<DistributeNodeInfoRespEntity> pageResult = distributeNodeInfoService.selectDistributeNodesByPage(pageQuery);
        List<DistributeNodeInfoRespEntity> respEntityList =  pageResult.getList();

        if (CollUtil.isNotEmpty(respEntityList)){
            List<Long> userIds=respEntityList.stream().map(DistributeNodeInfoRespEntity::getUserId).collect(Collectors.toList());
            Integer distributeType=-1;
            if (DistributeSaleRoleEnum.getByCode(pageQuery.getDistributeRoleCode())!=null){
                distributeType= DistributeTypeEnum.TYPE_SALE.getType();
            }else if (DistributeContentRoleEnum.getByCode(pageQuery.getDistributeRoleCode())!=null){
                distributeType= DistributeTypeEnum.TYPE_CTPD.getType();
            }
            if (distributeType==-1){
                throw new BaseException("角色不支持查询"+pageQuery.getDistributeRoleCode());
            }
            //查询下级用户
            Map<Long,Set<Long>> lowNodeUserIds=distributeNodeRoleChainDomainService.getLowNodeUserIds(distributeType,userIds,pageQuery.getDistributeRoleCode());
            System.out.println("下级："+ lowNodeUserIds);
            //查学员数量
            Map<Long,Long> studentSumMap=new HashMap<>();
            List<CompletableFuture<Void>> futures=lowNodeUserIds.keySet().stream().map(userId->
                CompletableFuture.runAsync(()->{
                   Set<Long> lowLevelList=lowNodeUserIds.get(userId);
                    System.out.println(userId+"下级："+ JSONUtil.toJsonStr(lowLevelList));
                   long count=0;
                   if (CollUtil.isNotEmpty(lowLevelList)){
                       count=distributeUserInviteService.count(Wrappers.lambdaQuery(DistributeUserInvite.class)
                               .in(DistributeUserInvite::getInviteUserId,lowLevelList)
                               .eq(DistributeUserInvite::getDataStatus,DistributeDataValidEnum.STATUS_VALID.getStatus()));
                       studentSumMap.put(userId,count);

                   }else {
                       studentSumMap.put(userId,count);
                   }
                  System.out.println(userId+"-学员："+count);


                })).toList();
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            //设置学员数量
            respEntityList.forEach(item->item.setStudentCount(studentSumMap.getOrDefault(item.getUserId(),0L)));
            //查订单金额
            SaleAmountQuery saleAmountQuery=new SaleAmountQuery();
            saleAmountQuery.setDistributeUserGroup(userIds);
            if (pageQuery.getDistributeOrderTimeStart()!=null) {
                saleAmountQuery.setStartDistributeTime(DateUtil.beginOfMonth(new Date()).toJdkDate());
            }
            if (pageQuery.getDistributeOrderTimeEnd()!=null) {
                saleAmountQuery.setEndDistributeTime(DateUtil.endOfMonth(new Date()).toJdkDate());
            }
            saleAmountQuery.setStatus(List.of("1"));
            if (pageQuery.getDistributeType()== DistributeTypeEnum.TYPE_SALE.getType()){
                List<DistributeSaleUserGroup> userAmountList=distributeOrderTaskSaleService.getSaleAmountGroupForUsers(saleAmountQuery);
                if (CollUtil.isNotEmpty(userAmountList)){
                    Map<Long, BigDecimal> map=userAmountList.stream().collect(HashMap::new, (k, v) -> k.put(v.getDistributeUserId(), v.getAmount()), HashMap::putAll);
                    Map<Long, BigDecimal> map1=userAmountList.stream().collect(HashMap::new, (k, v) -> k.put(v.getDistributeUserId(), v.getOrderAmount()), HashMap::putAll);
                    respEntityList.forEach(item->{
                        item.setMonthSumAmount(map.getOrDefault(item.getUserId(),BigDecimal.ZERO));
                        item.setOrderSumAmount(map1.getOrDefault(item.getUserId(),BigDecimal.ZERO));
                    });
                }else{
                    respEntityList.forEach(item->{
                        item.setMonthSumAmount(BigDecimal.ZERO);
                        item.setOrderSumAmount(BigDecimal.ZERO);
                    });
                }
            }else if (pageQuery.getDistributeType()== DistributeTypeEnum.TYPE_CTPD.getType()){
                List<DistributeContentUserGroup> userAmountList=distributeOrderTaskContentService.getContentAmountGroupForUsers(saleAmountQuery);
                if (CollUtil.isNotEmpty(userAmountList)){
                    Map<Long, BigDecimal> map=userAmountList.stream().collect(HashMap::new, (k, v) -> k.put(v.getDistributeUserId(), v.getAmount()), HashMap::putAll);
                    Map<Long, BigDecimal> map1=userAmountList.stream().collect(HashMap::new, (k, v) -> k.put(v.getDistributeUserId(), v.getOrderAmount()), HashMap::putAll);
                    respEntityList.forEach(item->{
                        item.setMonthSumAmount(map.getOrDefault(item.getUserId(),BigDecimal.ZERO));
                        item.setOrderSumAmount(map1.getOrDefault(item.getUserId(),BigDecimal.ZERO));
                    });
                }else{
                    respEntityList.forEach(item->{
                        item.setMonthSumAmount(BigDecimal.ZERO);
                        item.setOrderSumAmount(BigDecimal.ZERO);
                    });
                }
            }
        }
        pageResult.setList(respEntityList);
        return pageResult;
    }

    @Override
    public PageResult<DistributeNodeInfoRespEntity> querySaleProxyDistributeNodeInfoPageResult(DistributeNodeInfoQueryPage pageQuery) {
        Page<Object> page = PageHelper.startPage(pageQuery.getPage(), pageQuery.getSize());
        List<DistributeNodeInfo> nodeInfoList = distributeNodeInfoService.list(Wrappers
                .lambdaQuery(DistributeNodeInfo.class)
                .eq(DistributeNodeInfo::getDistributeRoleCode, DistributeSaleRoleEnum.ROLE_DSPD.getCode())
                .eq(DistributeNodeInfo::getDataStatus, DistributeDataValidEnum.STATUS_VALID.getStatus()));

        List<DistributeNodeInfoRespEntity> respEntityList = new ArrayList<>();
        for (DistributeNodeInfo nodeInfo : nodeInfoList) {
            respEntityList.add(BeanUtil.copyProperties(nodeInfo, DistributeNodeInfoRespEntity.class));
        }
        return PageResult.of(page.getTotal(), respEntityList);
    }

    @Override
    public PageResult<DistributeNodeInfoRespEntity> queryContentDistributeNodeInfoPageResult(DistributeNodeInfoQueryPage pageQuery) {
        Page<Object> page = PageHelper.startPage(pageQuery.getPage(), pageQuery.getSize());
        List<DistributeNodeInfo> nodeInfoList = distributeNodeInfoService.list(Wrappers
                .lambdaQuery(DistributeNodeInfo.class)
                .eq(DistributeNodeInfo::getDistributeRoleCode, DistributeContentRoleEnum.ROLE_CTPD.getCode())
                .eq(DistributeNodeInfo::getDataStatus, DistributeDataValidEnum.STATUS_VALID.getStatus()));

        List<DistributeNodeInfoRespEntity> respEntityList = new ArrayList<>();
        for (DistributeNodeInfo nodeInfo : nodeInfoList) {
            respEntityList.add(BeanUtil.copyProperties(nodeInfo, DistributeNodeInfoRespEntity.class));

        }
        return PageResult.of(page.getTotal(), respEntityList);
    }

    @Override
    public PageResult<DistributorRespEntity> queryDistributorPageResult(DistributorQueryPage pageQuery) {
        try (Page<Object> page = PageHelper.startPage(pageQuery.getPage(), pageQuery.getSize())) {
            List<DistributorRespEntity> distributorRespEntities = iDistributeRepository
                    .queryDistributorPageResult(pageQuery);
//            try (ExecutorService executorService= Executors.newVirtualThreadPerTaskExecutor()){
//                List<CompletableFuture<DistributorRespEntity>> future = distributorRespEntities.stream()
//                        .map(item -> CompletableFuture.supplyAsync(() -> getDistributorStatisticsInfo(item),CompletableFuture.delayedExecutor(0, java.util.concurrent.TimeUnit.MILLISECONDS, executorService))).toList();
//                CompletableFuture.allOf(future.toArray(new CompletableFuture[0])).join();
//            }
            List<CompletableFuture<DistributorRespEntity>> future = distributorRespEntities.stream()
                    .map(item -> CompletableFuture.supplyAsync(() -> getDistributorStatisticsInfo(item))).toList();
            CompletableFuture.allOf(future.toArray(new CompletableFuture[0])).join();
            return PageResult.of(page.getTotal(), distributorRespEntities);
        }
    }

    private DistributorRespEntity getDistributorStatisticsInfo(DistributorRespEntity distributorRespEntity) {
        //学员数量
        //获取所有销售
        List<DistributeNodeRoleChain> sale = distributeNodeRoleChainDomainService.getAllSaleNodeId(distributorRespEntity.getUserId());
        List<Long> userIds = new ArrayList<>();
        for (DistributeNodeRoleChain distributeNodeRoleChain : sale) {
            userIds.add(distributeNodeRoleChain.getRefUserId());
        }
        userIds.add(distributorRespEntity.getUserId());
        //获取邀请的学员
        List<DistributeUserInvite> studentsInvite = distributeUserInviteService.getInviteRecordListByDistributeUserId(userIds);
        if (studentsInvite.isEmpty()) {
            distributorRespEntity.setStudentSum(0L);
        } else {
            distributorRespEntity.setStudentSum((long) studentsInvite.size());
        }
        //总业绩
        SaleAmountQuery saleAmountQuery = new SaleAmountQuery();
        saleAmountQuery.setDistributeUserId(distributorRespEntity.getUserId());
        DistributeSale distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
        if (distributeSale != null) {
            distributorRespEntity.setPerformance(distributeSale.getAmount());
        }
        //近期业绩(上月）
        saleAmountQuery = new SaleAmountQuery();
        saleAmountQuery.setDistributeUserId(distributorRespEntity.getUserId());
        saleAmountQuery.setStartSaleTime(DateUtil.beginOfMonth(DateUtil.lastMonth()));
        saleAmountQuery.setEndSaleTime(DateUtil.endOfMonth(DateUtil.lastMonth()));
        distributeSale = distributeOrderTaskSaleService.getSaleAmount(saleAmountQuery);
        if (distributeSale != null) {
            distributorRespEntity.setRecentPerformance(distributeSale.getAmount());
        }
        return distributorRespEntity;
    }
    private void changeSaleDistributeUserDeptRoleBindToPlatform(Long userId, String distributeRoleCode){
        if (DistributeSaleRoleEnum.ROLE_DSPD.getCode().equals(distributeRoleCode)){
            //平台默认的会员部门
            DistributeDeptInfo deptInfo = distributeDeptInfoService.getOne(Wrappers.lambdaQuery(DistributeDeptInfo.class)
                    .eq(DistributeDeptInfo::getDeptOwnerId,userId).eq(DistributeDeptInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus()));
            if (deptInfo == null) {
                throw new BaseException("换绑切换部门出错：加盟商未查询到加盟商自己部门");
            }
            //部门上级是要换的
            distributeDeptInfoService.updateDeptUpLevelUser(deptInfo.getDeptId(),UserCs.PLATFORM_USER_ID);
            //加盟商的部门本身就是在平台下的，不需要切换。
                //distributeDeptUserRoleBindService.processUserDeptRole(DistributeTypeEnum.TYPE_SALE, userId, deptInfo.getDeptId(), SysRoleDistributeBindEnum.RB_MARKET_PROXY_MANAGER.getSysRoleCode(), distributeRoleCode);
        }else if (DistributeSaleRoleEnum.ROLE_SLMB.getCode().equals(distributeRoleCode)){
            //平台默认的会员部门
            Dept dept = deptRepository.getDeptById(DistributeDeptInnerRootEnum.YSXG_SLMB.getDeptId());
            if (dept == null) {
                throw new BaseException("换绑切换部门出错：员工升会员未查询到平台会员部门");
            }
            //重新绑定平台部门，不动原来部门
            distributeDeptUserRoleBindService.processUserDeptRole(DistributeTypeEnum.TYPE_SALE, userId, dept.getId(), SysRoleDistributeBindEnum.RB_MARKET_MEMBER.getSysRoleCode(),  distributeRoleCode);
            userRepository.updateUserDept(userId,dept.getId());
        }else {
            throw new BaseException("换绑切换部门出错：员工换绑平台部门不支持该角色");
        }
    }
    private void changeSaleDistributeUserDeptRoleBindToUpUser(Long userId,String distributeRoleCode,Long upperUserId,String upperUserRoleCode){
        if (distributeRoleCode.equals(DistributeSaleRoleEnum.ROLE_DSPD.getCode())&&(DistributeSaleRoleEnum.ROLE_MKMG.getCode().equals(upperUserRoleCode)|| UserCs.PLATFORM_USER_ID.equals(upperUserId))){
            //加盟商是自己的部门
            Long deptId=distributeDeptUserRoleBindService.getDeptBindIdForUser(userId,DistributeTypeEnum.TYPE_SALE);
            DistributeDeptInfo distributeDeptInfo = distributeDeptInfoService.getOne(Wrappers.lambdaQuery(DistributeDeptInfo.class)
                    .eq(DistributeDeptInfo::getDeptId, deptId).eq(DistributeDeptInfo::getDataStatus,DistributeDataStatusEnum.STATUS_CURT.getStatus())
            );
            if (distributeDeptInfo==null){
                throw new BaseException("换绑切换部门出错：员工换绑用户部门查上级部门实体出错");
            }
            //更改部门的上级信息,部门是他自己的，就更改一下上级信息，用户角色部门绑定关系不影响，他自己绑定自己的部门
            distributeDeptInfoService.updateDeptUpLevelUser(deptId,upperUserId);
            return;
        }
        if (distributeRoleCode.equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode())&&(DistributeSaleRoleEnum.ROLE_DSPD.getCode().equals(upperUserRoleCode))){
            //会员换加盟商要查加盟商的部门
            Long deptId=distributeDeptUserRoleBindService.getDeptBindIdForUser(upperUserId,DistributeTypeEnum.TYPE_SALE);
            DistributeDeptInfo distributeDeptInfo = distributeDeptInfoService.getOne(Wrappers.lambdaQuery(DistributeDeptInfo.class)
                    .eq(DistributeDeptInfo::getDeptId, deptId).eq(DistributeDeptInfo::getDataStatus,DistributeDataStatusEnum.STATUS_CURT.getStatus())
            );
            if (distributeDeptInfo==null){
                throw new BaseException("换绑切换部门出错：员工换绑用户部门查上级部门实体出错");
            }
            //不动原部门信息，更改绑定部门信息
            distributeDeptUserRoleBindService.processUserDeptRole(DistributeTypeEnum.TYPE_SALE, userId, distributeDeptInfo.getDeptId(), SysRoleDistributeBindEnum.RB_MARKET_MEMBER.getSysRoleCode(),  distributeRoleCode);
            userRepository.updateUserDept(userId,deptId);
            return;
        }else if (distributeRoleCode.equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode())&& UserCs.PLATFORM_USER_ID.equals(upperUserId)){
            Dept dept = deptRepository.getDeptById(DistributeDeptInnerRootEnum.YSXG_SLMB.getDeptId());
            distributeDeptUserRoleBindService.processUserDeptRole(DistributeTypeEnum.TYPE_SALE, userId, dept.getId(), SysRoleDistributeBindEnum.RB_MARKET_MEMBER.getSysRoleCode(),  distributeRoleCode);
            userRepository.updateUserDept(userId,dept.getId());
            return;
        }
        if (distributeRoleCode.equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())&&DistributeSaleRoleEnum.ROLE_DSPD.getCode().equals(upperUserRoleCode)){

            Long deptId=distributeDeptUserRoleBindService.getDeptBindIdForUser(upperUserId,DistributeTypeEnum.TYPE_SALE);
            DistributeDeptInfo distributeDeptInfo = distributeDeptInfoService.getOne(Wrappers.lambdaQuery(DistributeDeptInfo.class)
                    .eq(DistributeDeptInfo::getDeptId, deptId).eq(DistributeDeptInfo::getDataStatus,DistributeDataStatusEnum.STATUS_CURT.getStatus())
            );
            if (distributeDeptInfo==null){
                throw new BaseException("换绑切换部门出错：员工换绑用户部门查上级部门实体出错");
            }
            //员工原部门不影响，更改部门绑定
            distributeDeptUserRoleBindService.processUserDeptRole(DistributeTypeEnum.TYPE_SALE, userId, distributeDeptInfo.getDeptId(), SysRoleDistributeBindEnum.RB_MARKET_PROXY_EMPLOYEE.getSysRoleCode(),  distributeRoleCode);
            userRepository.updateUserDept(userId,distributeDeptInfo.getDeptId());
            return;
        }
        throw new BaseException("换绑切换部门出错：员工换绑用户部门不支持切换,原角色"+distributeRoleCode+"，上级角色"+upperUserRoleCode);
    }
    @Override
    public PageResult<DistributorStudentEntity> queryDistributorStudentPageResult(DistributorStudentQueryPage pageQuery) {
        //获取所有销售
        List<DistributeNodeRoleChain> sale = distributeNodeRoleChainDomainService.getAllSaleNodeId(pageQuery.getDistributorId());
        List<Long> userIds = new ArrayList<>();
        for (DistributeNodeRoleChain distributeNodeRoleChain : sale) {
            userIds.add(distributeNodeRoleChain.getRefUserId());
        }
        userIds.add(pageQuery.getDistributorId());
        DistributeNodeInfo distributeNodeInfo=distributeNodeInfoService.getOne(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                .eq(DistributeNodeInfo::getUserId, pageQuery.getDistributorId())
                .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE.getType())
                .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
        );
        //获取邀请的学员
        List<DistributeUserInvite> studentsInvite = distributeUserInviteService.getInviteRecordListByDistributeUserId(userIds);
        if (studentsInvite.isEmpty()) {
            return PageResult.of(0L, new ArrayList<>());
        }
        try (Page<Object> page = PageHelper.startPage(pageQuery.getPage(), pageQuery.getSize())) {
            List<DistributorStudentEntity> distributorRespEntities = iDistributeRepository
                    .queryDistributorStudentPageResult(pageQuery, studentsInvite.stream().map(DistributeUserInvite::getUserId).toList());
            distributorRespEntities.forEach(item -> {
                item.setStudentPhone(DesensitizedUtil.mobilePhone(SecureUtils.decryptFieldByAes(item.getStudentPhone())
                       ));
                item.setDistributorName(distributeNodeInfo.getFullName());
            });
            return PageResult.of(page.getTotal(), distributorRespEntities);
        }
    }
}